package com.bsoft.gol.hcb.service.docteam.dao;

/**
 * @Author:FangZhiyi
 * @Description
 * @Data Created in 2020/7/15 9:49
 * @Moddified By:
 */

import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import ctd.spring.boot.annotation.SsdevDao;
import ctd.util.annotation.RpcService;
import ctd.util.converter.ConversionUtils;
import hcn.bean.specialist.qo.GroupMemberRequest;
import hcn.bean.specialist.qo.QueryDocTeamListReq;
import hcn.bean.specialist.vo.ChronicTeamList;
import hcn.bean.specialist.vo.QueryDocTeamDetailResp;
import hcn.bean.specialist.vo.QueryDocTeamListResp;
import hcn.bean.specialist.vo.QueryDoctorDepartmentListResponse;
import hcn.docteam.DocTeamEntity;
import hcn.util.CommonUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.atag.dao.action.QoHibernateStatelessResultAction;
import org.atag.dao.util.CustomAliasToEntityMapResultTransformer;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.CriteriaSpecification;
import org.springframework.beans.factory.annotation.Value;
import pcn.bean.docTeam.QueryAllDocTeamReq;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@SsdevDao(serviceId = "docTeamDAOService")
public abstract class DocTeamDAO extends HibernateSupportDelegateDAO<DocTeamEntity> {
    @Value("${database_type}")
    public String databaseType;//1.mysql  2.达梦    默认mysql


    public  Long queryDocTeamListCount(QueryDocTeamListReq docTeamListReq){
        HibernateStatelessResultAction<Long> action = new AbstractHibernateStatelessResultAction<Long>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = getDocTeamListCountStringBuffer(docTeamListReq);
                Query sqlQuery = getQuery(ss, docTeamListReq, stringBuffer);
                sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> dbList = sqlQuery.list();
                if (CommonUtils.isNotEmpty(dbList)) {
                    setResult(Long.valueOf(String.valueOf(dbList.get(0).get("countValue"))));
                } else {
                    setResult(0L);
                }
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    };
    public List<QueryDocTeamListResp> queryDocTeamList(final QueryDocTeamListReq docTeamListReq) {
        HibernateStatelessResultAction<List<QueryDocTeamListResp>> action = new AbstractHibernateStatelessResultAction<List<QueryDocTeamListResp>>() {
            @Override
            public void execute(StatelessSession ss) {
                StringBuffer stringBuffer = getDocTeamListStringBuffer(docTeamListReq);
                Query sqlQuery = getQuery(ss, docTeamListReq, stringBuffer);
                int first = docTeamListReq.getPageNo() > 0 ? (docTeamListReq.getPageNo() - 1) * docTeamListReq.getPageSize() : 0;
                sqlQuery.setFirstResult(first);
                sqlQuery.setMaxResults(docTeamListReq.getPageSize());
                sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> dbList = sqlQuery.list();
                setResult(mapToList(dbList));
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    public List<QueryDocTeamListResp> queryDocTeamByDocidList(final QueryDocTeamListReq docTeamListReq) {
        HibernateStatelessResultAction<List<QueryDocTeamListResp>> action = new AbstractHibernateStatelessResultAction<List<QueryDocTeamListResp>>() {
            @Override
            public void execute(StatelessSession ss) {

                StringBuffer stringBuffer = new StringBuffer();
                String apply_status="1";

                if (CommonUtils.isNotEmpty(docTeamListReq.getApplyStatus())) {
                    apply_status=docTeamListReq.getApplyStatus();
                }
               //查询团队入组的人数、不是记录数
                stringBuffer.append(" SELECT distinct dt.medical_team_id medicalTeamId, dt.medical_team_name medicalTeamName " +
                        " FROM  doc_team_member dtm " +
                        " LEFT JOIN doc_team dt ON dt.medical_team_id = dtm.medical_team_id " +
                        " WHERE dt.team_type=1 and dt.enable_flag <>3 ");

                if (CommonUtils.isNotEmpty(docTeamListReq.getDoctorId())) {
                    //stringBuffer.append(" and dtm.doctor_id =:doctor_id ");
                }
                if (CommonUtils.isNotEmpty(docTeamListReq.getDocId())) {
                    stringBuffer.append(" and dtm.doc_id =:doc_id ");
                }
                if (StringUtils.isNotEmpty(docTeamListReq.getMedicalTeamName())) {
                    stringBuffer.append(" and dt.medical_team_name=:medicalTeamName");
                }
                if (docTeamListReq.getMedicalTeamId()!=null) {
                    stringBuffer.append(" and dt.medical_team_id=:medicalTeamId");
                }
                if (StringUtils.isNotEmpty(docTeamListReq.getTeamType())) {
                    stringBuffer.append(" and dt.team_type=:teamType");
                }
                Query sqlQuery = ss.createSQLQuery(stringBuffer.toString());

                if (CommonUtils.isNotEmpty(docTeamListReq.getDoctorId())) {
                   // sqlQuery.setParameter("doctor_id", docTeamListReq.getDoctorId());
                }
                if (CommonUtils.isNotEmpty(docTeamListReq.getDocId())) {
                    sqlQuery.setParameter("doc_id", docTeamListReq.getDocId());
                }

                if (CommonUtils.isNotEmpty(docTeamListReq.getMedicalTeamId())) {
                    sqlQuery.setParameter("medicalTeamId", docTeamListReq.getMedicalTeamId());
                }
                if (CommonUtils.isNotEmpty(docTeamListReq.getMedicalTeamName())) {
                    sqlQuery.setParameter("medicalTeamName", docTeamListReq.getMedicalTeamName());
                }
                if (CommonUtils.isNotEmpty(docTeamListReq.getTeamType())) {
                    sqlQuery.setParameter("teamType", docTeamListReq.getTeamType());
                }

                int first = docTeamListReq.getPageNo() > 0 ? (docTeamListReq.getPageNo() - 1) * docTeamListReq.getPageSize() : 0;
                sqlQuery.setFirstResult(first);
                sqlQuery.setMaxResults(docTeamListReq.getPageSize());
                sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> dbList = sqlQuery.list();
                setResult(mapToList(dbList));
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }



    private StringBuffer getDocTeamListStringBuffer(QueryDocTeamListReq docTeamListReq) {
        //默认函数为mysql的group_concat

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("select t.medical_team_id medicalTeamId,t.organization_id organizationId,t.visit_plan_share_flag visitPlanShareFlag,t.medical_team_name medicalTeamName,t.team_type teamType,t.team_type_name teamTypeName,t.department_id departmentId,t.department_name departmentName,");
        stringBuffer.append("(select count(1) as \"count\" from doc_team_member m where m.medical_team_id=t.medical_team_id) counts");

        stringBuffer.append(" from doc_team t  where t.enable_flag<>3");
        if (StringUtils.isNotEmpty(docTeamListReq.getMedicalTeamName())) {
            stringBuffer.append(" and t.medical_team_name like:medicalTeamName");
        }
        if (docTeamListReq.getMedicalTeamId()!=null) {
            stringBuffer.append(" and t.medical_team_id=:medicalTeamId");
        }
        if (CollectionUtils.isNotEmpty( docTeamListReq.getTeamIdList())){
            stringBuffer.append(" and t.medical_team_id in(:teamIdList)");
        }
        if (StringUtils.isNotEmpty(docTeamListReq.getTeamType())) {
            stringBuffer.append(" and t.team_type=:teamType");
        }
        if (null != docTeamListReq.getOrganizationId()) {
            stringBuffer.append(" and t.organization_id=:organizationId");
        }
        if (StringUtils.isNotEmpty(docTeamListReq.getKeyWord())) {
            stringBuffer.append(" and (t.medical_team_name like:keyWord or t.medical_team_id like:keyWord )");
        }
        stringBuffer.append("  ORDER  BY  gmt_create DESC  ");
        return stringBuffer;
    }


    private StringBuffer getDocTeamListCountStringBuffer(QueryDocTeamListReq docTeamListReq) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("SELECT count(1 ) countValue");
        stringBuffer.append(" from doc_team t  where t.enable_flag<>3");
        if (StringUtils.isNotEmpty(docTeamListReq.getMedicalTeamName())) {
            stringBuffer.append(" and t.medical_team_name like:medicalTeamName");
        }
        if (docTeamListReq.getMedicalTeamId()!=null) {
            stringBuffer.append(" and t.medical_team_id=:medicalTeamId");
        }
        if (StringUtils.isNotEmpty(docTeamListReq.getTeamType())) {
            stringBuffer.append(" and t.team_type=:teamType");
        }
        if (null != docTeamListReq.getOrganizationId()) {
            stringBuffer.append(" and t.organization_id=:organizationId");
        }
        if (StringUtils.isNotEmpty(docTeamListReq.getKeyWord())) {
            stringBuffer.append(" and (t.medical_team_name like:keyWord or t.medical_team_id like:keyWord )");
        }
        stringBuffer.append("  ORDER  BY  medical_team_id DESC  ");
        return stringBuffer;
    }

    private Query getQuery(StatelessSession ss, QueryDocTeamListReq docTeamListReq,
                           StringBuffer stringBuffer) {
        Query sqlQuery = ss.createSQLQuery(stringBuffer.toString());
        if (docTeamListReq.getMedicalTeamId()!=null) {//团队id
            sqlQuery.setParameter("medicalTeamId", docTeamListReq.getMedicalTeamId());
        }
        if (StringUtils.isNotEmpty(docTeamListReq.getMedicalTeamName())) {//团队名称
            sqlQuery.setString("medicalTeamName", "%"+ docTeamListReq.getMedicalTeamName() +"%");
        }
        if (StringUtils.isNotEmpty(docTeamListReq.getTeamType())) {//团队类型id
            sqlQuery.setParameter("teamType", docTeamListReq.getTeamType());
        }
        //机构代码
        if (null !=docTeamListReq.getOrganizationId()) {
            sqlQuery.setParameter("organizationId", docTeamListReq.getOrganizationId());
        }
        if (StringUtils.isNotEmpty(docTeamListReq.getKeyWord())) {
            sqlQuery.setParameter("keyWord", "%"+docTeamListReq.getKeyWord()+"%");
        }
        if (CollectionUtils.isNotEmpty( docTeamListReq.getTeamIdList())){
            sqlQuery.setParameterList("teamIdList", docTeamListReq.getTeamIdList());
        }
        return sqlQuery;
    }
    private List<QueryDocTeamListResp> mapToList(List<Map> maps) {
        List<QueryDocTeamListResp> docTeamListRespList = new ArrayList<>();
        for (Map map : maps) {
            docTeamListRespList.add(ConversionUtils.convert(map, QueryDocTeamListResp.class));
        }
        return docTeamListRespList;
    }

    @DAOMethod(sql = " from QueryDocTeamDetailResp where team_id =:id ")
    public abstract QueryDocTeamDetailResp queryDocTeamDetail(@DAOParam("teamId") Long teamId);

    @RpcService
    @DAOMethod(sql = "select medicalTeamId from DocTeamEntity  where medicalTeamId in (:medicalTeamId) and teamType ='1' ")
    public abstract List<Long> queryMedicalTeamId(@DAOParam("medicalTeamId") List<Long> medicalTeamId);


    /**
     * 根据参数查询医生团队
     */
    public List<DocTeamEntity> queryDocTeam(QueryAllDocTeamReq req) {
        QoHibernateStatelessResultAction<DocTeamEntity, QueryAllDocTeamReq> action = new QoHibernateStatelessResultAction<>(false, req, DocTeamEntity.class);
        String sql = "SELECT medical_team_id AS medicalTeamId, medical_team_name AS medicalTeamName FROM doc_team WHERE enable_flag = 1 ";
        action.setSql(sql);
        if(CommonUtils.isNotEmpty(req.getOrganizationId())){
            action.addCondition(" AND organization_id=:organizationId ");
        }
        if(CommonUtils.isNotEmpty(req.getTeamType())){
            action.addCondition(" AND team_type=:teamType ");
        }
        HibernateSessionTemplate.instance().execute(action);
        return action.getResultList();
    }


   /**
   * @description: 根据医生id查询到医生所拥有的团队
    * @param req
    * @return java.util.List<hcn.docteam.DocTeamEntity>
   * @author: zsf
   * @date: 2023/8/3 0003 15:51 TODO 为什么 team_type = 4 ？
   */
   @RpcService
    public List<DocTeamEntity> queryDocTeamByDoctId(QueryAllDocTeamReq req) {
        QoHibernateStatelessResultAction<DocTeamEntity, QueryAllDocTeamReq> action = new QoHibernateStatelessResultAction<>(false, req, DocTeamEntity.class);
        String sql = "SELECT DISTINCT b.medical_team_id as medicalTeamId,b.medical_team_name as medicalTeamName,b.team_type_name as teamTypeName from doc_team_member a LEFT JOIN doc_team b " +
                "on a.medical_team_id = b.medical_team_id WHERE  b.enable_flag = 1 ";
        action.setSql(sql);
        if(CommonUtils.isNotEmpty(req.getDoctorId())){
            action.addCondition(" and a.doctor_id =:doctorId ");
        }else {
            return null;
        }
       if(CommonUtils.isNotEmpty(req.getTeamType())){
           action.addCondition(" and b.team_type =:teamType ");
       }
        HibernateSessionTemplate.instance().execute(action);
        return action.getResultList();
    }

    @DAOMethod(sql = " from DocTeamEntity where enableFlag =1 ")
    public abstract List<DocTeamEntity> queryAllDocTeam();


    @DAOMethod(sql = " from DocTeamEntity where enableFlag =1 and organizationId=:organizationId")
    public abstract List<DocTeamEntity> queryAllDocTeamByOrganizationId(@DAOParam("organizationId") String organizationId);


    @RpcService
    public List<ChronicTeamList> queryTeamList(final GroupMemberRequest request) {
        HibernateStatelessResultAction<List<ChronicTeamList>> action = new AbstractHibernateStatelessResultAction<List<ChronicTeamList>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuffer sbf = new StringBuffer();
                sbf.append(" SELECT dt.medical_team_id medicalTeamId, dt.medical_team_name medicalTeamName," +
                        " dt.department_id departmentId, dt.department_name departmentName FROM doc_team dt " +
                        "LEFT JOIN doc_team_member dtm ON dt.medical_team_id = dtm.medical_team_id " +
                        "WHERE dt.enable_flag = 1 ");

                if (CommonUtils.isNotEmpty(request.getDocId())) {
                    sbf.append(" and dtm.doc_id =:doc_id ");
                }
                if (CommonUtils.isNotEmpty(request.getTeamType())) {
                    sbf.append(" and dt.team_type =:teamType ");
                }
                if (CommonUtils.isNotEmpty(request.getTeamIdList())) {
                    sbf.append(" and dt.medical_team_id in(:teamIdList) ");
                }
                Query query = ss.createSQLQuery(sbf.toString());

                if (CommonUtils.isNotEmpty(request.getTeamType())) {
                    query.setParameter("teamType", request.getTeamType());
                }
                if (CommonUtils.isNotEmpty(request.getDocId())) {
                    query.setParameter("doc_id", request.getDocId());
                }
                if (CommonUtils.isNotEmpty(request.getTeamIdList())) {
                    query.setParameterList("teamIdList", request.getTeamIdList());
                }
                query.setResultTransformer(CustomAliasToEntityMapResultTransformer.INSTANCE);

                List<Map> list = query.list();
                List<ChronicTeamList> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, ChronicTeamList.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    @RpcService
    public List<QueryDoctorDepartmentListResponse> queryDoctorDepartmentList(final String docId) {

        HibernateStatelessResultAction<List<QueryDoctorDepartmentListResponse>> action = new AbstractHibernateStatelessResultAction<List<QueryDoctorDepartmentListResponse>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuffer sbf = new StringBuffer();
                sbf.append(" SELECT DISTINCT dt.department_id departmentId, dt.department_name departmentName " +
                        "FROM doc_team_member m LEFT JOIN doc_team dt ON dt.medical_team_id = m.medical_team_id " +
                        "WHERE dt.enable_flag=1 AND m.doc_id = :doc_id ");

                Query query = ss.createSQLQuery(sbf.toString());
                query.setParameter("doc_id", docId);
                query.setResultTransformer(CustomAliasToEntityMapResultTransformer.INSTANCE);

                List<Map> list = query.list();
                List<QueryDoctorDepartmentListResponse> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, QueryDoctorDepartmentListResponse.class));
                    }
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();

    }
}
